package com.wang.mandkey.activity;

import java.net.InetAddress;
import java.net.Socket;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.wang.mandkey.R;
import com.wang.mandkey.net.Connecter;
import com.wang.mandkey.net.ConnecterPool;
import com.wang.mandkey.tool.MediaTool;
import com.wang.mandkey.tool.Tool;
import com.wang.mandkey.utils.ProjectEnvironment;
import com.wang.mandkey.utils.SharePersistent;
import com.wang.mandkey.utils.StringUtils;
import com.wang.mandkey.views.DemoView;
import com.waps.AdView;

/**
 * 设置视图
 * 
 * @author wangzy
 * 
 */
public class SettingActivity extends BaseActivity {

	private TextView mTextViewFocus;
	private EditText mEditTextIpInput;
	private EditText mEditTextPortInput, mEditTextScreenPort;
	private Button buttonLink;
	private String tag = "SettingActivity";
	private LinkHostTask linkHostTask;
	private int mIntPort = ProjectEnvironment.INT_DEFAULT_PORT_COMMAND;
	private ProgressDialog mProgressDialog = null;

	private SeekBar seekBar;
	private DemoView demoView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setUpView();
		MediaTool.addLoadListener(this);
	}

	@Override
	void setUpView() {

		setContentView(R.layout.setting);
		mEditTextIpInput = (EditText) findViewById(R.id.editTextIp);
		mEditTextPortInput = (EditText) findViewById(R.id.editTextPort);
		mEditTextPortInput.setText(String
				.valueOf(ProjectEnvironment.INT_DEFAULT_PORT_COMMAND));
		mEditTextScreenPort = (EditText) findViewById(R.id.editTextPortScreen);
		mEditTextScreenPort.setText(String
				.valueOf(ProjectEnvironment.INT_DEFAULT_PORT_IMG));
		mTextViewFocus = (TextView) findViewById(R.id.textViewFocus);

		String oldIp = SharePersistent.getPerference(this,
				ProjectEnvironment.STRING_IP_KEY);
		if (!StringUtils.isEmpty(oldIp)) {
			mEditTextIpInput.setText(oldIp);
		}

		seekBar = (SeekBar) findViewById(R.id.seekBar);

		int progress = (int) ProjectEnvironment.FLOAT_BUTTON_RADIUS;

		String radiusstr = SharePersistent.getPerference(this,
				ProjectEnvironment.STRING_PROJECT_RADIUS_KEY);
		if (!StringUtils.isEmpty(radiusstr)) {
			progress = Integer.parseInt(radiusstr);
		}
		seekBar.setProgress(progress);

		demoView = (DemoView) findViewById(R.id.demoView);

		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				demoView.invalidate();
				ProjectEnvironment.FLOAT_BUTTON_RADIUS = progress;
				SharePersistent.savePerference(SettingActivity.this,
						ProjectEnvironment.STRING_PROJECT_RADIUS_KEY,
						String.valueOf(progress));
			}
		});

		buttonLink = (Button) findViewById(R.id.buttonLink);

		buttonLink.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				linkHostTask = new LinkHostTask();
				// /^\d+$/
				String protString = mEditTextPortInput.getText().toString();

				if (protString.matches("//^\\d+$//")) {
					try {
						mIntPort = Integer.parseInt(protString);
					} catch (Exception e) {
						// 端口输入错误
						Toast.makeText(
								SettingActivity.this,
								getResources().getString(
										R.string.setting_activity_setting_port),
								Toast.LENGTH_SHORT).show();
						return;
					}
				}

				String protScreen = mEditTextScreenPort.getText().toString();

				if (protScreen.matches("//^\\d+$//")) {
					try {
						ProjectEnvironment.INT_DEFAULT_PORT_IMG = Integer
								.parseInt(protString);
					} catch (Exception e) {
						// 端口输入错误
						Toast.makeText(
								SettingActivity.this,
								getResources().getString(
										R.string.setting_activity_setting_port),
								Toast.LENGTH_SHORT).show();
						return;
					}
				}

				String hostIp = mEditTextIpInput.getText().toString();
				if (StringUtils.isEmpty(hostIp)
						|| !hostIp.matches(ProjectEnvironment.STRING_IP_REGX)) {
					// ip输入错误
					Toast.makeText(
							SettingActivity.this,
							getResources()
									.getString(
											R.string.setting_activity_setting_inputrtip),
							Toast.LENGTH_SHORT).show();
				} else {
					linkHostTask.execute(hostIp);
					ProjectEnvironment.STRING_HOST_IP = hostIp;// 修改默认的ip
					SharePersistent.savePerference(SettingActivity.this,
							ProjectEnvironment.STRING_IP_KEY, hostIp);

				}
			}
		});
		buttonLink.requestFocus();

		mProgressDialog = new ProgressDialog(SettingActivity.this);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mProgressDialog.setTitle(SettingActivity.this.getResources().getString(
				R.string.setting_activity_setting_linking));
		mProgressDialog.setCancelable(true);
		mProgressDialog.setMessage(SettingActivity.this.getResources()
				.getString(R.string.setting_activity_setting_link_yourhost));
		mProgressDialog.setOnDismissListener(new OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
				buttonLink.setEnabled(true);
				if(null!=linkHostTask){
					linkHostTask.cancel(true);
				}
			}
		});

		// 广告接口
		LinearLayout container = (LinearLayout) findViewById(R.id.AdLinearLayout);
		new AdView(this, container).DisplayAd();
	}

	@Override
	public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
		super.onLoadComplete(soundPool, sampleId, status);
		MediaTool.play(sampleId);
	}

	/**
	 * 三个泛型： 　　Param ，任务执行器需要的数据类型 　　Progress 后台计算中使用的进度单位数据类型 　　Result
	 * 后台计算返回结果的数据类型 　　有些参数是可以设置为不使用的，只要传递为Void型即可，比如AsyncTask 　　四个步骤：
	 * 　　onPreExecute()，执行预处理，它运行于UI线程，可以为后台任务做一些准备工作，比如绘制一个进度条控件。
	 * 　　doInBackground(Params...)，后台进程执行的具体计算在这里实现，doInBackground(Params...)
	 * 是AsyncTask的关键，此方法必须重载。在这个方法内可以使用 publishProgress(Progress...)改变当前的进度值。
	 * 　　onProgressUpdate(Progress...)，运行于UI线程。如果在doInBackground(Params...)
	 * 中使用了publishProgress(Progress...)，就会触发这个方法。在这里可以对进度条控件根据进度值做出具体的响应。
	 * 　　onPostExecute
	 * (Result)，运行于UI线程，可以对后台任务的结果做出处理，结果就是doInBackground(Params...)
	 * 的返回值。此方法也要经常重载，如果Result为null表明后台任务没有完成(被取消或者出现异常)。
	 * 
	 * 写这个类，主要锻炼一下AsncTask
	 * 
	 * @author wangzy
	 * 
	 */

	class LinkHostTask extends AsyncTask<String, Integer, String> {

		@Override
		protected void onPreExecute() {
			// 预处理
			buttonLink.setEnabled(false);

			mProgressDialog.show();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... param) {
			// 后台计算
			String host = param[0];
			try {
				ConnecterPool.clearPool();
				mIntPort = Integer.parseInt(mEditTextPortInput.getText()
						.toString().trim());
				Socket socket = new Socket(InetAddress.getByName(host),
						mIntPort);
				Connecter conector = new Connecter(socket);
				ConnecterPool.putConnecter(conector.getmStringRemoteHost(),
						conector);
			} catch (Exception e) {
				Log.e(tag, "message:" + e.getMessage());
				cancel(true);
				e.printStackTrace();
			}
			// publishProgress(10);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			// 处理结果
			buttonLink.setEnabled(true);
			mProgressDialog.dismiss();

			if (ConnecterPool.getConnectorPoolSize() > 0) {
				// 连接成功
				finish();
			} else {
				// 连接失败
				MediaTool.load(SettingActivity.this, R.raw.done);
				Tool.ToastShow(SettingActivity.this,
						R.string.setting_activity_setting_link_fail);
			}

		}

	};
}
